//
//  KFDAccountCenterViewController.m
//  
//
//  Created by JIRENTIANXIANG on 6/24/15.
//
//

#import "KFDAccountCenterViewController.h"
#import "KFDUIConfigurator.h"
#import "KFDMeViewController.h"
#import "KFDAccountManager.h"
#import "KFDUIConfigurator.h"
#import "KFDUpdatePasswordViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "JTToast.h"
#import "KFDAvatarViewController.h"
#import "ui_config.h"

@interface KFDAccountCenterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong,nonatomic) UIImageView* avatar;
@property (strong,nonatomic) UILabel* nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;
@property (weak, nonatomic) IBOutlet UILabel *realNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *genderLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (assign,nonatomic) BOOL hide;

@end

@implementation KFDAccountCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    KFDUIConfigurator* uiConfigurator=[KFDUIConfigurator configuratorForViewController:self];
    [uiConfigurator configureNavigationBarWithBackAction:@selector(goBack)];
    self.title=@"用户中心";
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.avatar=[UIImageView new];
    self.avatar.frame=CGRectMake(0, 0, 80, 80);
    self.avatar.center=CGPointMake(uiConfigurator.WIDTH/2, 100);
    self.avatar.layer.cornerRadius=80/2;
    self.avatar.layer.masksToBounds=YES;
    UITapGestureRecognizer* tapRecognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarPressed)];
    [self.avatar addGestureRecognizer:tapRecognizer];
    self.avatar.userInteractionEnabled=YES;
    [self.view addSubview:self.avatar];
    
    [self setupNameLabel];
    
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    if (accountManager.injectionUrl&&accountManager.withdrawUrl) {
        self.hide=NO;
    }else{
        self.hide=YES;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageSizeExceedLimit) name:KFDImageSizeExceedLimitNotification object:nil];
}

-(void)setupNameLabel
{
    self.nameLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.nameLabel.center=CGPointMake(SCREEN_WIDTH/2, 150);
    self.nameLabel.textAlignment=NSTextAlignmentCenter;
    self.nameLabel.font=[UIFont systemFontOfSize:15];
    self.nameLabel.textColor=KFD_WHITE;
    [self.view addSubview:self.nameLabel];
}

-(void)imageSizeExceedLimit
{
    [[JTToast makeText:@"图片大小超过限制"] showInView:self.view size:CGSizeMake(160, 40)];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KFDImageSizeExceedLimitNotification object:nil];
}

-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    self.nicknameLabel.text=accountManager.nickname;
    self.realNameLabel.text=accountManager.realName;
    self.genderLabel.text=accountManager.gender;
    self.phoneNumberLabel.text=accountManager.phoneNumber;
    KFDUserAddress* address=accountManager.userAddress;
    if (address.province&&address.city&&address.district) {
        self.addressLabel.text=[NSString stringWithFormat:@"%@ %@ %@",address.province,address.city,address.district];
    }
    
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:accountManager.avatar] placeholderImage:[UIImage imageNamed:@"avatar"]];
    
    self.nameLabel.text=accountManager.nickname;
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

-(void)avatarPressed
{
//    UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction* chooseFromAlbum=[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//        UIImagePickerController* imagePicker=[[UIImagePickerController alloc] init];
//        imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
//        imagePicker.delegate=self;
//        [self presentViewController:imagePicker animated:YES completion:nil];
//    }];
//    [alertController addAction:chooseFromAlbum];
//    UIAlertAction* takePhoto=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//        UIImagePickerController* imagePicker=[[UIImagePickerController alloc] init];
//        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
//        imagePicker.delegate=self;
//        [self presentViewController:imagePicker animated:YES completion:nil];
//    }];
//    [alertController addAction:takePhoto];
//    UIAlertAction* cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//        
//    }];
//    [alertController addAction:cancel];
//    [self presentViewController:alertController animated:YES completion:nil];
    KFDAvatarViewController* avatarVC=[[KFDAvatarViewController alloc] init];
    [self.navigationController pushViewController:avatarVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-------------------------------------------------------------------------------------------
#pragma mark - Table view data source
//-------------------------------------------------------------------------------------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 4;
        case 1:
            return self.hide?1:3;
        case 2:
            return 1;
        default:
            return 0;
    }
}
//-------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------
#pragma mark - Table view delegate
//-------------------------------------------------------------------------------------------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
//-------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------
#pragma mark - Image picker controller delegate
//-------------------------------------------------------------------------------------------
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage* image=info[@"UIImagePickerControllerOriginalImage"];
    KFDClient* client=[KFDClient sharedClient];
    [client uploadAvatar:image successHandler:^(NSString *avatarUrl) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[JTToast makeText:@"头像修改成功"] showInView:self.view size:CGSizeMake(120,40)];
            self.avatar.image=image;
        });
    } failureHandler:^(KFDResponseBody *response) {
        
    }];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//-------------------------------------------------------------------------------------------

-(void)prepareForSegue:(nonnull UIStoryboardSegue *)segue sender:(nullable id)sender
{
    if ([segue.identifier isEqualToString:@"KFDSegueUpdatePassword"]) {
        ((KFDUpdatePasswordViewController*)segue.destinationViewController).title=@"修改密码";
    }
}

@end
